package com.ojoin.trade.common.utils;

import java.util.HashMap;

import javax.mail.internet.InternetAddress;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ojoin.trade.common.utils.mail.MailBean;
import com.ojoin.trade.common.utils.mail.SendMail;

public class EmailSendUtil {

	private final static Logger log = LoggerFactory
			.getLogger(EmailSendUtil.class);

	public static boolean send(String destination, String subject,
			String shortMessage) {
		return send(destination, subject, shortMessage, null);

	}

	public static boolean send(String destination, String subject,
			String shortMessage, String attch) {
		MailBean mb = new MailBean();
		mb.setHost(Config.getProperty("mail.smtp")); // 设置SMTP主机
		mb.setUsername(Config.getProperty("mail.username")); // 设置发件人邮箱的用户名
		mb.setPassword(Config.getProperty("mail.password")); // 设置发件人邮箱的密码
		mb.setFrom(Config.getProperty("mail.from")); // 设置发件人的邮箱

		mb.setTo(destination); // 设置收件人的邮箱
		mb.setSubject(subject); // 设置邮件的主题
		mb.setContent(shortMessage); // 设置邮件的正文

		if (StringUtils.isNotEmpty(attch)) {
			mb.attachFile(attch);
		}

		SendMail sm = new SendMail();
		return sm.sendMail(mb);
	}

	public static boolean sendByAttchByte(String from, String fromshortname, String to, String cc, String subject,
			String shortMessage, HashMap<String, byte[]> attchMap) {
		MailBean mb = new MailBean();
		mb.setHost(Config.getProperty("mail.smtp")); // 设置SMTP主机
		mb.setPassword(Config.getProperty("mail.password")); // 设置发件人邮箱的密码
		
		//用户名和邮箱必须一致，否则邮件发送失败
		mb.setUsername(from); // 设置发件人邮箱的用户名
		mb.setFrom(from); // 设置发件人的邮箱
		mb.setFromshortname(fromshortname); //设置发件人简称
		
		mb.setTo(to); // 设置收件人的邮箱
		mb.setCc(cc); //设置抄送人邮箱
		mb.setSubject(subject); // 设置邮件的主题
		mb.setContent(shortMessage); // 设置邮件的正文
		mb.setBytefiles(attchMap); // 设置邮件的附件

		SendMail sm = new SendMail();
		return sm.sendMail(mb);
	}
	
	/**
	 * 验证码
	 * 
	 * @param mail
	 * @param checkcode
	 * @return
	 */
	public static String sendCheckCode(String mail, String checkcode) {
		// 发送内容
		String msgcontent = "【九盈】您的验证码为：" + checkcode;
		String sub = "【九盈】验证信息";

		log.info("正在发送邮件 收件人:{} 内容:{}", new String[] { mail, msgcontent });
		if (send(mail, sub, msgcontent)) {
			return checkcode;
		}
		log.info("发送邮件失败 收件人:{} 内容:{}", new String[] { mail, msgcontent });

		return null;
	}
}
